<template>

  <div id="picture-manage" @click.stop="handleClickOutside">
    <a-flex justify="space-between">
      <h2>图片管理</h2>
      <a-space>
        <a-button type="primary" href="/add_picture" target="_blank">+ 创建图片</a-button>
        <a-button type="primary" href="/add_picture/batch" target="_blank" ghost>+ 批量创建图片</a-button>
      </a-space>
    </a-flex>

    <a-form style="margin-bottom: 10px" layout="inline" :model="searchParams">
      <a-form-item label="关键词" name="searchText">
        <a-input
          v-model:value="searchParams.searchText"
          placeholder="从名称和简介搜索"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="类型" name="category">
        <a-input v-model:value="searchParams.category" placeholder="请输入类型" allow-clear />
      </a-form-item>
      <a-form-item label="标签" name="tags">
        <a-select
          v-model:value="searchParams.tags"
          mode="tags"
          placeholder="请输入标签"
          style="min-width: 180px"
          :options="tagOptions"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="审核状态" name="reviewStatus">
        <a-select
          v-model:value="searchParams.reviewStatus"
          :options="PIC_REVIEW_STATUS_OPTIONS"
          placeholder="请输入审核状态"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit" @click="doSearch">搜索</a-button>
        <a-button style="margin-left: 10px" html-type="submit" @click="reset">重置</a-button>
      </a-form-item>
    </a-form>


    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'url'">
          <a-image :src="record.url" :width="120" />
        </template>
        <!-- 标签 -->
        <template v-if="column.dataIndex === 'tags'">
          <a-space wrap>
            <a-tag v-for="tag in JSON.parse(record.tags || '[]')" :key="tag">{{ tag }}</a-tag>
          </a-space>
        </template>
        <!-- 图片信息 -->
        <template v-if="column.dataIndex === 'picInfo'">
          <div>格式：{{ record.picFormat }}</div>
          <div>宽度：{{ record.picWidth }}</div>
          <div>高度：{{ record.picHeight }}</div>
          <div>宽高比：{{ record.picScale }}</div>
          <div>大小：{{ (record.picSize / 1024).toFixed(2) }}KB</div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <!-- 审核信息 -->
        <template v-if="column.dataIndex === 'reviewMessage'">

          <div>审核状态：
            <p style="display: inline-block" v-if="record.reviewStatus===PIC_REVIEW_STATUS_ENUM.PASS">
              <a-tag color="blue">{{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}</a-tag>
            </p>
            <p style="display: inline-block" v-if="record.reviewStatus===PIC_REVIEW_STATUS_ENUM.REVIEWING">
              <a-tag >{{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}</a-tag>
            </p>
            <p style="display: inline-block" v-if="record.reviewStatus===PIC_REVIEW_STATUS_ENUM.REJECT">
              <a-tag color="red">{{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}</a-tag>
            </p>
          </div>
          <div>审核信息：{{ record.reviewMessage }}</div>
          <div>审核人：{{ record.reviewerId }}</div>
        </template>

        <template v-else-if="column.key === 'action'">
          <a-space wrap>
            <a-button
              v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.PASS"
              type="link"
              @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.PASS)"
            >
              通过
            </a-button>
            <a-button
              v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.REJECT"
              type="link"
              danger
              @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.REJECT)"
            >
              拒绝
            </a-button>
            <a-button type="link" :href="`/add_picture?id=${record.id}`" target="_blank"
            >编辑
            </a-button>
            <a-button  danger @click="doDelete(record.id)">删除</a-button>
          </a-space>
        </template>

      </template>
    </a-table>
  </div>

</template>
<script lang="ts" setup>
import { computed, createVNode, onMounted, reactive, ref } from 'vue'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import {
  deletePictureByIdUsingPost, doPictureReviewUsingPost,
  getTagAndCategoryUsingGet,
  pictureListPageUsingPost
} from '@/api/pictureController.ts'
import { inject } from 'vue'

import { PIC_REVIEW_STATUS_MAP, PIC_REVIEW_STATUS_ENUM, PIC_REVIEW_STATUS_OPTIONS } from '@/constants/picture.ts'
// 注入 reload 函数
const reload = inject('reload')
const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '图片',
    dataIndex: 'url'
  },
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true
  },
  {
    title: '类型',
    dataIndex: 'category'
  },
  {
    title: '标签',
    dataIndex: 'tags'
  },
  {
    title: '图片信息',
    dataIndex: 'picInfo'
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    width: 80
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime'
  },
  {
    title: '审核信息',
    dataIndex: 'reviewMessage'
  },
  {
    title: '操作',
    key: 'action'
  }
]

// 数据
const dataList = ref([])
const total = ref(0)
const categoryOptions = ref<string[]>([])
const tagOptions = ref<string[]>([])

// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 4,
  sortField: 'createTime',
  sortOrder: 'descend'
})

// 分页参数
const pagination = computed(() => {
  return {
    position: ['bottomCenter'],
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条`
  }
})

// 获取数据
const fetchData = async () => {
  const res = await pictureListPageUsingPost({
    nullSpaceId:true,
    ...searchParams
  })
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// 获取数据
const doSearch = () => {
  // 重置搜索条件
  searchParams.current = 1
  fetchData()
}

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

const doDelete = async (id: number) => {
  Modal.confirm({
    title: '是否删除该图片',
    icon: createVNode(ExclamationCircleOutlined),
    content: '系统提示',
    okText: '确认',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      const res = await deletePictureByIdUsingPost({
        id: id
      })
      if (res.data.code === 0) {
        message.success('删除成功！')
        reload?.()

      } else {
        message.error('删除失败!')
      }
    },
    onCancel() {
    }
  })
}
const getTagCategoryOptions = async () => {
  const res = await getTagAndCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // 转换成下拉选项组件接受的格式
    tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
      return {
        value: data,
        label: data
      }
    })
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
      return {
        value: data,
        label: data
      }
    })
  } else {
    message.error('加载选项失败，' + res.data.message)
  }
}

const handleClickOutside = (event) => {
  // 检查点击是否发生在“空白处”
  // 这里是一个简单的例子，你可能需要根据你的应用逻辑来调整
  if (!event.target.closest('#picture-manage ') && !event.target.closest('a') && !event.target.closest('button')) {
    fetchData()
  }
}

const reset = () => {
  searchParams.searchText = null
  searchParams.category = null
  searchParams.tags = []
  searchParams.reviewStatus=null

  fetchData()
}

const handleReview = async (record: API.Picture, reviewStatus: number) => {
  const reviewMessage = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '管理员审核通过' : '管理员审核拒绝'
  const res = await doPictureReviewUsingPost({
    id: record.id,
    reviewStatus: reviewStatus,
    reviewMessage: reviewMessage
  })
  if (res.data.code === 0 && res.data.data) {
    message.success("审核通过！")
    reload?.()
  }else {
    message.error("操作失败"+res.data.message)
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside, true)
  fetchData()
  getTagCategoryOptions()
})
</script>

<style>
#picture-manage {

}

</style>
